package com.bmft.ftcloud.controller;


import com.bmft.ftcloud.config.BeanConfig;
import com.bmft.ftcloud.model.constant.Constant;
import com.bmft.ftcloud.model.dto.FileDTO;
import com.bmft.ftcloud.util.file.FileUtil;
import com.bmft.ftcloud.util.response.Result;
import com.bmft.ftcloud.util.token.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.ServletOutputStream;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.bmft.ftcloud.util.response.Result.fail;
import static com.bmft.ftcloud.util.response.Result.success;

/**
 * @author Jarvan
 * @version 1.0
 * @create 2020/11/29 17:04
 */
@CrossOrigin("http://localhost:8080")
@RestController
@RequestMapping("/file/*")
@Slf4j
public class FileController {
    @Autowired
    FileUtil fileUtil;
    @Autowired
    TokenUtil tokenUtil;
    @Autowired
    BeanConfig beanConfig;


    /**
     * 上传文件
     *
     * @param request
     * @return
     */
    @PostMapping("/upload")
    public Result<String> uploadFile(HttpServletRequest request) {
        log.info("===========upload()=============");
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        MultipartFile file = files.get(0);
        Map<String, String> map = tokenUtil.parseToken(request.getHeader(Constant.TOKEN), request.getHeader("Host"));
        String username = map.get("username");
        if (username != null) {
            fileUtil.createLocalFile(username, file);
            return success("文件上传成功");
        }
        return fail("文件上传失败");
    }

    /**
     * 刷新文件
     *
     * @param request
     * @return
     */
    @PostMapping("/refresh")
    public Result<List<FileDTO>> refresh(HttpServletRequest request) throws FileNotFoundException {
        log.info("===========refresh()===========");
        //通过token获得用户文件夹
        String token = request.getHeader(Constant.TOKEN);
        Map<String, String> map = tokenUtil.parseToken(request.getHeader(Constant.TOKEN), request.getHeader("Host"));
        String username = map.get("username");
        String basePath = beanConfig.getBaseFilePath();
        String folderPath = basePath + "/" + username;
        log.info("=========folderPath=" + folderPath + "============");
        File file = new File(folderPath);
        if (file.exists()) {
            ArrayList<FileDTO> fileDTOS = new ArrayList<>();
            for (String s : file.list()) {
                //文件名，文件地址这里我们单层文件先不考虑文件地址的问题
                fileDTOS.add(new FileDTO(s, "#"));
            }
            return success(fileDTOS);
        }
        return fail(null);
    }

    /**
     * 文件下载
     *
     * @param fileName RESTFul 风格的下载方式，将下载的文件名称放到请求连接里
     * @return
     */
    @GetMapping("/download/{fileName}")
    public Result<String> download(@PathVariable("fileName") String fileName
            , HttpServletRequest request
            , HttpServletResponse response) throws IOException {
        log.info("===========download()==============");
        //拿到username
        Map<String, String> map = tokenUtil.parseToken(request.getHeader(Constant.TOKEN), request.getHeader("Host"));
        String username = map.get("username");

        //获取返回值的输出流
        ServletOutputStream outputStream = response.getOutputStream();
        //获取要下载的文件
        log.info("========文件地址==========");
        log.info(beanConfig.getBaseFilePath() + "/" + username + "/" + fileName);
        File file = new File(beanConfig.getBaseFilePath() + "/" + username + fileName);
        log.info(file.exists() + "======");
        if (!file.exists()){
            file.createNewFile();
        }
        FileInputStream is = new FileInputStream(file);
        byte[] buffer = new byte[1024 * 10];
        int length = 0;
        //缓存文件到返回输出流
        while ((length = is.read(buffer)) > -1) {
            outputStream.write(buffer, 0, length);
            outputStream.flush();
        }
        outputStream.close();
        is.close();
        //设置返回类型
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        log.info("=========response流结束=========");
        return success("下载成功");

    }
}
